<?php


namespace App\Utils;


use App\Services\EsConnector;
class EsUtil //提供ES的便捷操作
{
    /**
     * @var \EasySwoole\ElasticSearch\ElasticSearch
     */
    private $elasticsearch;

    public function __construct()
    {
        //$this->elasticsearch = app(EsConnector::class)->getInstance();
        $this->elasticsearch = EsConnector::getInstance();
    }
    private function buildBody($whereArr){

        if (!empty($whereArr)){
            $musts = [];
            foreach($whereArr as $where){
                $field = $where[0];
                $condition = $where[1];
                $value = $where[2];
                switch($condition){
                    case 'eq':
                        $musts[] = ['term'=>[$field=>$value]];
                        break;
                    case 'neq':
                        $musts[] = ['bool'=>['must_not'=>[
                            ['match_phrase'=>['getOrLost'=>['query'=>$value]]]
                        ]]];
                        break;
                    case 'like':
                        $musts[] = ['match_phrase'=>[$field=>["query"=>$value]]];
                        break;
                    case 'in':
                        $musts[] = ['terms'=>[$field=>$value]];
                        break;
                    case 'gt':
                        $musts[] = ['range'=>[$field=>["gt"=>$value]]];
                        break;
                    case 'lt':
                        $musts[] = ['range'=>[$field=>["lt"=>$value]]];
                        break;
                    case 'gte':
                        $musts[] = ['range'=>[$field=>["from"=>$value]]];
                        break;
                    case 'lte':
                        $musts[] = ['range'=>[$field=>["to"=>$value]]];
                        break;
                    default:
                        throw new \Exception("condition error!");
                }
            }

            $body = [];
            $body['query'] = [
                'bool'=>[
                    'must'=>$musts
                ]
            ];
            return $body;
        } else {
            return ['query'=>['bool'=>['must'=>[['match_all'=>(object)[]]]]]];
        }
    }

    /**
     * @param array $body
     * @return mixed
     */
    public function batchInsert($body)
    {
        $bean = new \EasySwoole\ElasticSearch\RequestBean\Bulk();
        $bean->setBody($body);
        $json = $this->elasticsearch->client()->bulk($bean)->getBody();
        return json_decode($json,true);
    }


    public function deleteIndex($index , $whereArr=[]){
        $bean = new \EasySwoole\ElasticSearch\RequestBean\DeleteByQuery();
        $bean->setIndex($index);
        $body = $this->buildBody($whereArr);
        $bean->setBody($body);
        $res = $this->elasticsearch->client()->deleteByQuery($bean)->getBody();
        //echo $res;
    }

    /**
     * @param $index
     * @param array $whereArr
     * @param int $page
     * @param int $limit
     * @param array $sorts
     * @return array
     */
    public function  getPaginate($index , $whereArr = [], $page=1, $limit=10,$sorts=[])
    {
        $bean = new \EasySwoole\ElasticSearch\RequestBean\Search();
        $bean->setIndex($index);
        $body = $this->buildBody($whereArr);
        $body['from'] = ($page - 1) * $limit;
        $body['size'] = $limit;
        if (!empty($sorts)){
            $body['sort'] = $sorts;
        }
        $body['track_total_hits'] = true;
//        if ($index=='equipment'){
//            var_dump($body);
//        }
//
        $bean->setBody($body);
        $res = json_decode($this->elasticsearch->client()->search($bean)->getBody(),true);

        $total = data_get($res,'hits.total.value');

        $returnRes = [];
        $returnRes['code'] = 0;
        $data = [];
        if ($total > 0){
            foreach (data_get($res,'hits.hits') as $row){
                $source = $row['_source'];
                $source['_id'] = $row['_id'];
                $data[] = $source;
            }
        }
        $returnRes['count'] = $total;
        $returnRes['data'] = $data;
        return $returnRes;
    }

}
